from fastapi.security import OAuth2PasswordBearer
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")


# main.py
from fastapi import FastAPI, Depends, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession
from typing import List

from models import User
from schemas import UserCreate, UserPublic, UserUpdate, Token
from database import get_session, engine
from sqlmodel import SQLModel,select
from auth import create_access_token, verify_password
from crud import get_user_by_username, create_user
from dependencies import get_current_user
from auth import hash_password
app = FastAPI(title="User Center API")

# 创建表
@app.on_event("startup")
async def on_startup():
    async with engine.begin() as conn:
        await conn.run_sync(SQLModel.metadata.create_all)

# 注册
@app.post("/register", response_model=UserPublic, status_code=status.HTTP_201_CREATED)
async def register(user_in: UserCreate, session: AsyncSession = Depends(get_session)):
    existing_user = await get_user_by_username(user_in.username, session)
    if existing_user:
        raise HTTPException(status_code=400, detail="Username already registered")
    return await create_user(user_in, session)

# 登录 → 获取 token
@app.post("/token", response_model=Token)
async def login(username: str, password: str, session: AsyncSession = Depends(get_session)):
    user = await get_user_by_username(username, session)
    if not user or not verify_password(password, user.hashed_password):
        raise HTTPException(status_code=401, detail="Incorrect username or password")
    token = create_access_token(data={"sub": user.username})
    return {"access_token": token, "token_type": "bearer"}

# 获取当前用户
@app.get("/me", response_model=UserPublic)
async def read_users_me(current_user: User = Depends(get_current_user)):
    return current_user

# 更新用户信息
@app.patch("/me", response_model=UserPublic)
async def update_user_me(
    user_update: UserUpdate,
    current_user: User = Depends(get_current_user),
    session: AsyncSession = Depends(get_session)
):
    if user_update.full_name is not None:
        current_user.full_name = user_update.full_name
    if user_update.password is not None:
        current_user.hashed_password = hash_password(user_update.password)
    session.add(current_user)
    await session.commit()
    await session.refresh(current_user)
    return current_user

# 【管理员】获取所有用户（演示用）
@app.get("/users/", response_model=List[UserPublic])
async def list_users(session: AsyncSession = Depends(get_session)):
    result = await session.exec(select(User))
    return result.all()